# src/core/factory.py
import os
from typing import Dict, Type
from .interfaces import IDocumentReader, IDocumentWriter, ILLMProcessor, IQuestionSplitter
from .document_processor import WordReader, WordWriter, SimpleMarkdownSplitter
from src.processing.llm_processor import MoonshotProcessor
from src.api.openai_api import OpenAIClient

class ProcessorFactory:
    """处理器工厂类，用于创建流水线的各个组件。"""
    
    _readers: Dict[str, Type[IDocumentReader]] = {
        '.docx': WordReader,
        '.doc': WordReader,
    }
    
    _writers: Dict[str, Type[IDocumentWriter]] = {
        '.docx': WordWriter,
        '.doc': WordWriter,
    }

    @staticmethod
    def create_reader(input_path: str) -> IDocumentReader:
        """根据输入路径创建文档读取器 (支持文件和URL)。"""
        # 判断输入是否是URL
        if input_path.lower().startswith(('http://', 'https://')):
            # 在函数内部导入，避免循环依赖或不必要的加载
            from src.core.web.web_reader import WebReader
            from src.core.web.strategies import UcampusStrategy
            
            # 未来可以根据url的域名选择不同策略，例如:
            # if 'unipus.cn' in input_path:
            #     strategy = UcampusStrategy()
            # else:
            #     raise ValueError(f"不支持此网站的抓取: {input_path}")
            
            # 目前，我们直接使用U校园策略
            strategy = UcampusStrategy() 
            return WebReader(strategy=strategy)
        
        # 如果不是URL，则按原有的文件逻辑处理
        file_type = os.path.splitext(input_path)[1]
        reader_class = ProcessorFactory._readers.get(file_type.lower())
        if not reader_class:
            raise ValueError(f"不支持的输入文件类型: {file_type}")
        return reader_class()

    @staticmethod
    def create_writer(file_type: str) -> IDocumentWriter:
        """根据文件类型创建文档写入器。"""
        writer_class = ProcessorFactory._writers.get(file_type.lower())
        if not writer_class:
            raise ValueError(f"不支持的输出文件类型: {file_type}")
        return writer_class()

    @staticmethod
    def create_splitter() -> IQuestionSplitter:
        """创建问题分割器。"""
        return SimpleMarkdownSplitter()

    @staticmethod
    def create_llm_processor(client: OpenAIClient) -> ILLMProcessor:
        """创建 LLM 处理器。"""
        return MoonshotProcessor(client)